//
//  MYGTabBarController.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/2/27.
//

import UIKit
import SnapKit
import QMUIKit

struct MYGTabbarItem {
    var viewController: UIViewController
    var name: String
    var image: String
}


class MYGTabBarController: UIViewController {
    // MARK: - Property
    var current: UIViewController?
    var vcs: [UIViewController] = []
    var selIndex: Int = 0 {
        didSet {
            if oldValue == selIndex {
                return
            }
            
            let btns = backgroundImageView.subviews.filter{$0 is QMUIButton}.map{$0 as! QMUIButton}
            btns.forEach { item in
                if (item.tag-1000) == selIndex {
                    item.isSelected = true
                } else {
                    item.isSelected = false
                }
            }
            
            if let current = current {
                let vc = vcs[selIndex]
                current.willMove(toParent: nil)
                transition(from: current, to: vc, duration: 0.3, animations: nil)
                vc.didMove(toParent: self)
                self.current = vc
            }
            
            
            view.bringSubviewToFront(backgroundImageView)
            view.bringSubviewToFront(whiteView)
        }
    }
    
    var hiddenButton: Bool = false {
        didSet {
            let btns = backgroundImageView.subviews.filter{$0 is QMUIButton}.map{$0 as! QMUIButton}
            btns.forEach { item in
                item.isHidden = hiddenButton
            }
            
            backgroundImageView.isHidden = hiddenButton
            whiteView.isHidden = hiddenButton
        }
    }
    var selectedViewController: UIViewController? {
        vcs[selIndex]
    }
    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        configChildVc()

        view.bringSubviewToFront(backgroundImageView)
        view.bringSubviewToFront(whiteView)
    }
    
    // MARK: - UI
    private func configUI() {
        view.addSubview(whiteView)
        view.addSubview(backgroundImageView)
        
        backgroundImageView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(whiteView.snp.top).offset(3)
//            make.height.equalTo(tabbarHeight)
        }
        
        whiteView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(bottomSafeheight+3)
        }
        
        backgroundImageView.setContentHuggingPriority(.required, for: .vertical)
        backgroundImageView.setContentCompressionResistancePriority(.required, for: .vertical)
    }
    
    // MARK: - 配置
    private func configChildVc() {
        let home = MYGHomePageViewController()
        let homeItem = MYGTabbarItem(viewController: home, name: "首页", image: "Tabbar/home")
        
        let friend = MYGMessageIndexController()
        let friendItem = MYGTabbarItem(viewController: friend, name: "好友沟通", image: "Tabbar/chat")
        
        let time = MYGScheduleViewController()
        let timeItem = MYGTabbarItem(viewController: time, name: "日程", image: "Tabbar/send")
        
        let patient = MYGMicrostationViewController()
        let patientItem = MYGTabbarItem(viewController: patient, name: "个人微站", image: "Tabbar/web")
        
        let mine = MYGMyPageViewController()
        let mineItem = MYGTabbarItem(viewController: mine, name: "我的", image: "Tabbar/mine")
        
        addChildVc([homeItem, friendItem, timeItem, patientItem, mineItem])
    }
    
    private func addChildVc(_ items: [MYGTabbarItem]) {
        for (index, item) in items.enumerated().reversed() {
            let nav = MYGNavigationController(rootViewController: item.viewController)
            addChild(nav)
            view.addSubview(nav.view)
            nav.view.frame = CGRectMake(0, 0, screenWidth, screenHeight-tabbarHeight-bottomSafeheight)
            vcs.insert(nav, at: 0)
            current = nav
            
            let btn = QMUIButton()
            btn.spacingBetweenImageAndTitle = 5
            btn.imagePosition = .top
            btn.setTitle(item.name, for: .normal)
            btn.setTitleColor(.rgba(78, 121, 237, 1), for: .selected)
            btn.setTitleColor(.rgba(159, 169, 187, 1), for: .normal)
            btn.setImage(UIImage(named: item.image), for: .normal)
            btn.setImage(UIImage(named: "\(item.image)_sel"), for: .selected)
            btn.titleLabel?.font = .regular(11)
            btn.tag = 1000+index
            btn.addTarget(self, action: #selector(clickTab), for: .touchUpInside)
            backgroundImageView.addSubview(btn)
            
            btn.snp.makeConstraints { make in
                if index == 2 {
                    make.centerX.equalToSuperview()
                }
                else {
//                    make.right.equalToSuperview().inset((screenWidth/5)*CGFloat(3-index))
                    make.left.equalToSuperview().offset((screenWidth/5)*CGFloat(index))

                }
                
                if index != 2 {
                    make.height.equalTo(44)
                }
                
                make.width.equalTo(screenWidth/5)
                make.bottom.equalTo(backgroundImageView).inset(3)
            }
            
            if index == 0 {
                btn.isSelected = true
            }
        }
    }
    
    // MARK: - lazy load
    private lazy var backgroundImageView: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "Tabbar/bg"))
        imgV.isUserInteractionEnabled = true
        return imgV
    }()
    
    private lazy var whiteView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    
    override var shouldAutorotate: Bool {
        guard let nav = selectedViewController as? UINavigationController else {
            return selectedViewController?.shouldAutorotate ?? false
        }
        
        return nav.topViewController?.shouldAutorotate ?? false
    }
    
    // 支撑哪些屏幕方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.supportedInterfaceOrientations ?? .portrait }
        return navigationController.topViewController?.supportedInterfaceOrientations ?? .portrait
    }
    
    // 默许的屏幕方向（当时ViewController有必要是经过模态出来的UIViewController（模态带导航的无效）办法展现出来的，才会调用这个办法）
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        guard let navigationController = selectedViewController as? UINavigationController else { return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait }
        return navigationController.topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
}

extension MYGTabBarController {
    @objc
    private func clickTab(_ btn: QMUIButton) {
        let index = btn.tag - 1000
        if index == 1 {
            if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
                let vc = MYGBaseInfoController()
                UIViewController.currentViewController?.navigationController?.pushViewController(vc)
                return
            }
//            NotificationCenter.default.post(name: NSNotification.Name.init("requestMeetingsNum"), object: nil)
        }
        
        selIndex = btn.tag - 1000

    }
}
